Passing Props to Components in React
Passing Props to Components is an important concept in React JS. Props, short for properties, allow a parent component to pass data, values, functions, objects, arrays, and other JavaScript values to a child component. Props help developers create reusable, dynamic, and customizable UI components.
Learn more through JustAcademy React JS Training or Register for React JS Course Demo.
1. What Are Props in React?
Props are inputs passed from one component to another, usually from a parent component to a child component. They allow the same component to display different content depending on the values it receives.
For example, a Greeting component can receive a person's name through props and display a personalized greeting.
Example:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return <Greeting name="Rahul" />;
}
export default App;
Output: Hello, Rahul!
In this example, App is the parent component, Greeting is the child component, and name is the prop passed to Greeting.
2. Why Are Props Used in React?
- Data sharing: Pass information from parent components to child components.
- Component reusability: Reuse the same component with different data.
- Dynamic content: Display different text, images, prices, and other values.
- Customization: Change the appearance or behavior of a component through props.
- Function communication: Pass callback functions from parent components to child components.
- Maintainability: Separate data from the UI structure and keep components organized.
3. How to Pass Props to Components
Props are passed by adding attributes to a component when using it in JSX. The child component receives these values through its props parameter.
Example:
function Student(props) {
return (
<div>
<h2>Student Name: {props.name}</h2>
<p>Course: {props.course}</p>
</div>
);
}
function App() {
return (
<Student name="Amit" course="React JS" />
);
}
export default App;
Output:
Student Name: Amit
Course: React JS
Here, the parent component passes name and course to the Student component. The child component reads these values using props.name and props.course.
4. Understanding Parent and Child Components
A parent component is a component that renders another component. The rendered component is called the child component. Props provide a standard way for the parent to send data to the child.
Example:
function Child(props) {
return <p>Message: {props.message}</p>;
}
function Parent() {
return <Child message="Welcome to React JS" />;
}
export default Parent;
Output: Message: Welcome to React JS
Data flow: Parent Component → Props → Child Component → Rendered UI
5. Passing Multiple Props
A component can receive multiple props at the same time. Each prop can represent a different piece of information.
Example:
function Employee(props) {
return (
<div>
<h2>{props.name}</h2>
<p>Role: {props.role}</p>
<p>Experience: {props.experience} years</p>
</div>
);
}
function App() {
return (
<Employee
name="Priya"
role="Frontend Developer"
experience={3}
/>
);
}
export default App;
Output:
Priya
Role: Frontend Developer
Experience: 3 years
String values can be passed using quotation marks, while numbers and other JavaScript expressions are passed inside curly braces.
6. Passing Props Using Destructuring
Destructuring is a JavaScript feature that allows developers to extract properties from an object. React developers commonly use it to access props directly without repeatedly writing props.propertyName.
Example without destructuring:
function User(props) {
return <h2>Hello, {props.name}</h2>;
}
Example with destructuring:
function User({ name }) {
return <h2>Hello, {name}</h2>;
}
function App() {
return <User name="Neha" />;
}
export default App;
Output: Hello, Neha
Both approaches work correctly. Destructuring is often preferred because it makes components easier to read.
7. Passing Different Data Types as Props
React props can carry different types of JavaScript values, including strings, numbers, booleans, arrays, objects, functions, and JSX elements.
| Data Type |
Example |
Purpose |
| String |
name="Amit" |
Pass text values. |
| Number |
age={25} |
Pass numerical values. |
| Boolean |
isActive={true} |
Represent true or false conditions. |
| Array |
items={["HTML", "CSS"]} |
Pass a collection of values. |
| Object |
user={{ name: "Amit" }} |
Pass structured information. |
| Function |
onClick={handleClick} |
Pass a function for a child to call. |
| JSX |
content={Hello} |
Pass UI elements. |
Example: Passing a Number and Boolean
function Product({ price, available }) {
return (
<div>
<p>Price: ₹{price}</p>
<p>Available: {available ? "Yes" : "No"}</p>
</div>
);
}
function App() {
return <Product price={999} available={true} />;
}
export default App;
Output:
Price: ₹999
Available: Yes
8. Passing Arrays as Props
Arrays can be passed to child components to display lists of information. The child can use JavaScript array methods such as map() to render the values.
Example:
function Skills({ items }) {
return (
<ul>
{items.map((skill) => (
<li key={skill}>{skill}</li>
))}
</ul>
);
}
function App() {
const skills = ["HTML", "CSS", "JavaScript", "React"];
return <Skills items={skills} />;
}
export default App;
Output: A list containing HTML, CSS, JavaScript, and React.
The key prop helps React identify list items when rendering and updating the list.
9. Passing Objects as Props
Objects are useful when several related values belong together, such as a user's name, email address, and role.
Example:
function UserProfile({ user }) {
return (
<div>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>Role: {user.role}</p>
</div>
);
}
function App() {
const userData = {
name: "Rohit",
email: "[email protected]",
role: "Developer"
};
return <UserProfile user={userData} />;
}
export default App;
Here, the userData object is passed through the user prop, and the child component accesses its individual properties.
10. Passing Functions as Props
Functions can be passed as props when a child component needs to notify a parent about an event or request an action. This is commonly used for button clicks, form submissions, and other user interactions.
Example:
function Child({ onGreet }) {
return <button onClick={onGreet}>Say Hello</button>;
}
function App() {
function handleGreet() {
alert("Hello from the parent component!");
}
return <Child onGreet={handleGreet} />;
}
export default App;
When the user clicks the button, the child calls the function received through onGreet, and the parent's function executes.
Important: Pass the function reference as onClick={handleGreet}. Writing onClick={handleGreet()} calls the function during rendering instead of waiting for the click.
11. Passing Props with Default Values
A default prop value can be specified using a default value in the function parameter. It is used when a prop is omitted or explicitly passed as undefined.
Example:
function Greeting({ name = "Guest" }) {
return <h2>Welcome, {name}!</h2>;
}
function App() {
return (
<div>
<Greeting />
<Greeting name="Aarav" />
</div>
);
}
export default App;
Output:
Welcome, Guest!
Welcome, Aarav!
A default value does not replace an explicitly passed null or another defined value.
12. Passing Props with the Spread Operator
The JSX spread syntax allows multiple properties from an object to be passed to a component. It can reduce repetitive code when forwarding props.
Example:
function User({ name, age, city }) {
return (
<p>{name}, {age}, {city}</p>
);
}
function App() {
const userData = {
name: "Karan",
age: 24,
city: "Mumbai"
};
return <User {...userData} />;
}
export default App;
Output: Karan, 24, Mumbai
Use the spread operator carefully. Passing only the props a component needs can make data flow easier to understand.
13. Passing JSX Through the Children Prop
When content is placed between a component's opening and closing tags, React passes that content to the component through the special children prop. This is useful for reusable layouts, cards, panels, and wrappers.
Example:
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}
function App() {
return (
<Card>
<h2>React JS</h2>
<p>Learn reusable components.</p>
</Card>
);
}
export default App;
The Card component receives the heading and paragraph as children and displays them inside its wrapper.
14. Props Are Read-Only
Props are read-only inputs. A child component should not directly modify the props it receives. If information needs to change, the parent should provide updated props, often by updating its own state.
Incorrect approach:
function Counter({ count }) {
count = count + 1;
return <p>Count: {count}</p>;
}
Do not modify a prop to manage component updates. Instead, use state in the component responsible for the change or request the parent to update the value.
Correct example:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
In this example, useState manages the changing count. Props and state serve different purposes: props provide inputs, while state stores information managed by a component.
15. Difference Between Props and State
| Props |
State |
| Passed into a component, usually by its parent. |
Managed by a component or another state-management owner. |
| Read-only from the receiving component's perspective. |
Updated using the relevant state setter or state-management mechanism. |
| Used to configure a component. |
Used to store changing information. |
| Can contain strings, numbers, objects, arrays, functions, and JSX. |
Can store different kinds of JavaScript values. |
| New props may arrive when the parent re-renders. |
State updates can trigger a re-render. |
16. Common Mistakes When Passing Props
- Incorrect prop name: Passing userName but trying to read props.name.
- Missing curly braces: Writing
age="25" when a number is intended, instead of age={25}.
- Modifying props: Trying to change a prop directly inside the child component.
- Calling a callback too early: Using
onClick={handleClick()} instead of onClick={handleClick} for a click handler.
- Missing list keys: Rendering mapped elements without stable, unique key values.
- Incorrect destructuring: Using a property that does not exist in the props object.
- Overusing spread syntax: Forwarding many unnecessary props and making component behavior unclear.
- Confusing props and state: Trying to use a prop as though it were locally managed state.
17. Practical Example: Product Card Using Props
This example demonstrates how props can make one ProductCard component reusable for different products.
ProductCard.jsx
function ProductCard({ name, price, category }) {
return (
<div className="product-card">
<h2>{name}</h2>
<p>Category: {category}</p>
<p>Price: ₹{price}</p>
<button>Buy Now</button>
</div>
);
}
export default ProductCard;
App.jsx
import ProductCard from "./ProductCard";
function App() {
return (
<div>
<ProductCard
name="Laptop"
price={55000}
category="Electronics"
/>
<ProductCard
name="Headphones"
price={2500}
category="Accessories"
/>
</div>
);
}
export default App;
Result: Two product cards display different product names, prices, and categories using the same reusable component.
Advantages of This Example
- Reduces duplicated UI code.
- Makes the component easy to reuse.
- Allows product information to change without rewriting the component.
- Keeps product data separate from presentation.
18. Best Practices for Passing Props
- Use clear and meaningful prop names.
- Keep components focused on a specific responsibility.
- Use destructuring when it improves readability.
- Provide sensible default values when appropriate.
- Never directly mutate props or objects received through props.
- Pass callback functions when a child needs to request an action from a parent.
- Use stable keys when rendering lists.
- Use children for flexible wrapper and layout components.
- Avoid forwarding unnecessary props.
- Consider Context when many intermediate components must forward the same data repeatedly.
19. Interview Questions and Answers
Q1. What are props in React?
Props are read-only inputs that allow components to receive data from parent components or other component owners.
Q2. How do you pass props to a component?
Pass values as attributes in JSX, such as .
Q3. Can a component receive multiple props?
Yes. A component can receive multiple props, including strings, numbers, arrays, objects, functions, and JSX.
Q4. What is prop destructuring?
Destructuring extracts individual properties from the props object, for example function User({ name, age }).
Q5. Can props be modified inside a child component?
No. Props should be treated as read-only. The component that owns the data should provide updated values.
Q6. What is the children prop?
It is the special prop that contains content nested between a component's opening and closing tags.
Q7. Can functions be passed as props?
Yes. Functions are commonly passed as callbacks for click events, form submissions, and communication from child components to parents.
Q8. What is the difference between props and state?
Props are inputs received by a component, while state is information managed by a component or another state owner and updated through the relevant state-management mechanism.
Q9. What are default prop values?
Default values provide fallback values when a prop is missing or undefined, such as function Greeting({ name = "Guest" }).
Q10. What is prop drilling?
Prop drilling occurs when data is passed through several intermediate components that do not directly need it, simply to reach a deeply nested component.
20. Practice Exercises
- Create a Student component that accepts name, age, and course props.
- Create a reusable Profile component that accepts a name and job title.
- Pass an array of programming languages to a child component and display them in a list.
- Create a ProductCard component that accepts a product name, price, and category.
- Pass a callback function from a parent to a child and call it when a button is clicked.
- Create a Card component that renders nested JSX using the children prop.
- Set default values for optional props and test what happens when a prop is omitted.
- Build a simple employee directory using reusable components and object props.
21. Quick Revision Checklist
- Understand the meaning and purpose of props.
- Know how to pass and access props.
- Practice destructuring props.
- Learn how to pass strings, numbers, booleans, arrays, objects, functions, and JSX.
- Understand default values and spread syntax.
- Know how the children prop works.
- Remember that props are read-only.
- Understand the difference between props and state.
- Build reusable components using practical examples.
22. Conclusion
Passing props to components is a fundamental React JS skill. Props help developers transfer data, customize reusable components, pass callback functions, and build well-organized user interfaces. Understanding props, destructuring, default values, children, and read-only behavior provides a strong foundation for learning component composition, state management, and advanced React development.
Continue learning with JustAcademy React JS Training and explore the course through Register for React JS Course Demo.
Reference
For official React documentation, read Passing Props to a Component – React.